package com.pomelo.kill.service.impl;

import com.pomelo.kill.exception.KillException;
import com.pomelo.kill.model.Order;
import com.pomelo.kill.service.CarService;
import com.pomelo.kill.service.OrderService;
import com.pomelo.kill.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import com.pomelo.kill.mapper.CarMapper;
import com.pomelo.kill.model.Car;

import java.util.List;

@Service
@Slf4j
public class CarServiceImpl implements CarService {

    @Resource
    private CarMapper carMapper;

    @Resource
    private RedisService redisService;

    @Resource
    private OrderService orderService;

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return carMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(Car record) {
        return carMapper.insert(record);
    }

    @Override
    public int insertSelective(Car record) {
        return carMapper.insertSelective(record);
    }

    @Override
    public Car selectByPrimaryKey(Integer id) {
        return carMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(Car record) {
        return carMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(Car record) {
        return carMapper.updateByPrimaryKey(record);
    }

    /**
     * 加入购物车
     *
     * @param record 要加入购物车的实体对象
     */
    @Override
    public int addToCar(Car record) throws KillException {
        // 加入购物车进行验证，如果已经存在待付款/已付款，不允许加入
        Order order = redisService.obligationByGid(record.getUid(), record.getGid());// 待付款订单列表
        if (order != null) {
            log.error("存在待付款订单");
            throw new KillException("存在待付款订单");
        }
        order = orderService.selectByUidAndGid(record.getUid(), record.getGid()); // 已付款订单
        if (order != null) {
            log.error("每个用户限购一件");
            throw new KillException("每个用户限购一件");
        }
        return insertSelective(record);
    }

    @Override
    public List<Car> selectBuUid(Integer uid) {
        return carMapper.selectByUserid(uid);
    }

}
